<?php

namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Api\Helpers\ApiResponse;
use Illuminate\Support\Facades\DB;
include_once(app_path() . '/Http/Services/Alipay/AopClient.php');
include_once(app_path() . '/Http/Services/Alipay/request/AlipayTradeCreateRequest.php');
include_once(app_path() . '/Http/Services/Alipay/request/AlipaySystemOauthTokenRequest.php');
include_once(app_path() . '/Http/Services/Alipay/request/AlipayTradeQueryRequest.php');


class AlipayController extends Controller
{
    use ApiResponse;
    private $userId = '';
    public function auth(Request $re)
    {
        $aop = new \AopClient ();
        $aop->gatewayUrl = config('app.gateway_url');
        $aop->appId = config('app.aop_app_id'); //开发者私钥
        $aop->rsaPrivateKey = config('app.aop_rsa_private_key');  //支付宝公钥
        //$aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnAzR7nlfcv49C3Guh1hEsgX2lyxuTHI0Uc8uxm9lo53q1SEdlHC3uvIhRCmlWgWa/2mzXAH/DaLQqc9NC5X1CDnuvFwQgDRqKvJJHLRUsJq3l/91CagPBh3XgfABf8HRXGBgyILhAc62sTtmLZQzYoXF7AcMoW9U3gJdTsvhaoV+oqVf9Cf/GdHcz9vV1Z6hA0XMrWRNXeSx7lx0mjwFvcEHGRTljTaL75eZdSxRrzWa7mQ12Z9hZMrA8juvu7yhsJvYbTq1AC6Vv5ADzuittmW+BHMQOq31I8WGIZQk/jNhZUUB3HDVhcRv4LM1B6txoMbzXWmajfT74HxLDsRe8QIDAQAB';
        $aop->alipayrsaPublicKey = config('app.aop_rsa_public_key');
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $request = new \AlipaySystemOauthTokenRequest ();
        $request->setGrantType("authorization_code");
        $request->setCode($re->input('authCode'));
        $request->setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = isset($result->$responseNode->code)?$result->$responseNode->code:10000;//json异常的时候才会出现code,下同，不做过多解释
        if(!empty($resultCode)&&$resultCode == 10000 && !isset($result->error_response->code)){
            return ['error' => 0, 'res' => $result->$responseNode];
        } else if(isset($result->error_response->code) && $result->error_response->code){
            return ['error' => -1, 'res' => $result->error_response];
        } else {
            return ['error' => -1, 'res' => $result->$responseNode];
        }
    }

    public function pay(Request $request)
    {
        if (!$request->has('orderInfo')) {
            return $this->failed('The orderInfo parameter no found');
        }
        if (!$request->has('userId')) {
            return $this->failed('The userId parameter no found');
        }
        $orderInfo = $request->input('orderInfo');
        $account = $orderInfo['account'];
        $productId = $orderInfo['productId'];
        $price = $orderInfo['price'];
        $productName = $orderInfo['productName'];
        $userId =  $request->input('userId');
        $this->userId = $userId;
        $aop = new \AopClient();
        $aop->gatewayUrl = config('app.gateway_url');
        //$aop->appId = '2021000199697553';//正式环境
        $aop->appId = config('app.aop_app_id');
        $aop->rsaPrivateKey = config('app.aop_rsa_private_key');
        $aop->alipayrsaPublicKey = config('app.aop_rsa_public_key');
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request = new \AlipayTradeCreateRequest();
        $request_data = [
            'out_trade_no' => $this->orderCreate(), //商户订单号
            'total_amount' => 0.01,               //订单总金额
            'subject' => '套餐：'.$productName,     //订单标题
            'buyer_id' => $userId,                  //买家的支付宝唯一用户号
            'account'=>$account,
            'product_id'=>$productId,
            'product_price'=>$price,
            'product_name'=>$productName
        ];
        $request->setNotifyUrl('http://www.onlineadmin.com/api/notify');
        $request->setBizContent(json_encode($request_data));
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            return ['error' => 0, 'res' => $result];
        } else {
            return ['error' => -1, 'res' => $result];
        }
    }
    //支付宝回调
    public function callback()
    {
        $data = $_POST;
        $aop = new \AopClient();
        $aop->alipayPublicKey = config('app.aop_rsa_public_key');
        $flag = $aop->rsaCheckV1($data, NULL, "RSA2");
        $myfile = fopen(storage_path('/logs/alipay.log'), "a");
        fwrite($myfile, "\r\n");
        fwrite($myfile, json_encode($data));
        fclose($myfile);
        date_default_timezone_set('Asia/Shanghai');
        $order_info = array();
        if (!empty($data) && $flag) {
            //以下为回调业务逻辑代码
            $order_info['trade_no'] = $data['trade_no'];
            $order_info['order_number'] = $data['out_trade_no'];
            $order_info['buyer_id'] = $data['buyer_id'];
            $order_info['order_amount'] = $data['amount'];
            $order_info['pay_amount'] = $data['buyer_pay_amount'];
            $order_info['total_amount'] = $data['total_amount'];
            //套餐信息
            $order_info['product_name'] = $data['product_name'];
            $order_info['product_id'] = $data['product_id'];
            $order_info['product_price'] = $data['product_price'];
            $order_info['account'] = $data['account'];
            $order_info['type'] = 1;
            if ($data['trade_status'] == 'TRADE_SUCCESS') {
                //支付成功业务处理，调Boss平台充值接口,可以发起退款操作
                $Recharge = new RechargeController();
                $data['userId'] = $this->userId;
                $Recharge->doRecharge($data);
                $order_info['pay_status'] = 2;
                $order_info['trade_status'] = 1;
            }else {
                $order_info['pay_status'] = 1;
                if ($data['trade_status'] == 'TRADE_CLOSED'){
                    $order_info['trade_status'] = 0;//交易关闭
                }
                if ($data['trade_status'] == 'TRADE_FINISHED'){
                    $order_info['trade_status'] = 2;//交易完结，不能发起退出，不会收到任何通知了
                }
                if ($data['trade_status'] == 'WAIT_BUYER_PAY'){
                    $order_info['trade_status'] = 3;//支付宝有交易记录，待付款
                }
            }
            //绑定用户卡信息
            $bind = array();
            $bind['userId'] = $this->userId;
            $bind['account'] = $data['account'];
            $bind['bindTime'] = date('Y-m-d H:i:s',time());
            DB::table('users_bind')->insert($bind);
            $order_info['pay_time'] = $data['gmt_create'];
            DB::table('order_info')->insert($order_info);
        }
    }

    public function orderCreate()
    {
        $expiredTimes = mktime(23, 59, 59) - mktime(date('H'), date('i'), date('s'));
        date_default_timezone_set('Asia/Shanghai');
        try {
            $orderIdNum = Redis::get('orderID') ? intval(Redis::get('orderID')) : 0;
            $time = date('Ymd', time());
            if ($orderIdNum <= 9) {
                $order = "00000" . $orderIdNum;
            } else if ($orderIdNum <= 99) {
                $order = "0000" . $orderIdNum;
            } else if ($orderIdNum <= 999) {
                $order = "000" . $orderIdNum;
            } else if ($orderIdNum <= 9999) {
                $order = "00" . $orderIdNum;
            } else if ($orderIdNum <= 99999) {
                $order = "0" . $orderIdNum;
            } else {
                $order = $orderIdNum;
            }
            $orderID = intval($time . $order);
            Redis::setex('orderID', $expiredTimes, intval(Redis::get('orderID')) + 1);
            return $orderID;
        } catch (\Exception $e) {
            return "The orderId create fail!";
        }
    }

    /**
     * @ queryPaymentByTradeNo
     * @description 查询单笔订单
     * @param {*} $tradeNo
     * @returns
     */
    public function queryPaymentByTradeNo(Request $request)
    {
        $input = $request->input();
        $aop = new \AopClient ();
        $aop->gatewayUrl = config('app.gateway_url');
        $aop->appId = config('app.aop_app_id'); //开发者私钥
        $aop->rsaPrivateKey = config('app.aop_rsa_private_key');  //支付宝公钥
        $aop->alipayrsaPublicKey = config('app.aop_rsa_public_key');
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='utf-8';
        $aop->format='json';
        $request = new \AlipayTradeQueryRequest ();
        $queryContent = array();
        $queryContent['trade_no'] = $input['trade_no'];
//        $queryContent['trade_no'] = '2020012122001463531413002366';
        $request->setBizContent(json_encode($queryContent));
        $result = $aop->execute ( $request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            return true;
        } else {
            return false;
        }
    }

    /**
     * @ queryPaymentByTradeNo
     * @description 查询单笔订单详情
     * @param {*} $tradeNo
     * @returns
     */
    public function queryPayDetail($tradeNo)
    {
        $aop = new \AopClient ();
        $aop->gatewayUrl = config('app.gateway_url');
        $aop->appId = config('app.aop_app_id'); //开发者私钥
        $aop->rsaPrivateKey = config('app.aop_rsa_private_key');  //支付宝公钥
        $aop->alipayrsaPublicKey = config('app.aop_rsa_public_key');
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='utf-8';
        $aop->format='json';
        $request = new \AlipayTradeQueryRequest ();
        $queryContent = array();
        $queryContent['trade_no'] = $tradeNo;
//        $queryContent['trade_no'] = '2020012122001463531413002366';
        $request->setBizContent(json_encode($queryContent));
        $result = $aop->execute ( $request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            return response([
                'success' => true,
                'result'=> $result->$responseNode
            ]);
        } else {
            return response([
                'success' => false
            ]);
        }
    }
}